package com.exercises;


import java.util.HashMap;
import java.util.Map;

class Exercise87 {
    public static void main(String[] args) {
    }

    String s1, s2;
    int[][][] dp;

    public boolean isScramble(String s1, String s2) {
        this.s1 = s1;
        this.s2 = s2;
        int length = s1.length();
        this.dp = new int[length - 1][length - 1][length];


        return dfs(0, 0, length);
    }

    public boolean dfs(int i1, int i2, int length) {
        if (dp[i1][i2][length] != 0) {
            return dp[i1][i2][length] == 1;
        }

        if (s1.substring(i1, i1 + length).equals(s2.substring(i2, i2 + length))) {
            dp[i1][i2][length] = 1;
            return true;
        }

        if (!simpleCheck(i1, i2, length)) {
            dp[i1][i2][length] = -1;
            return false;
        }

        for (int i = 0; i < length; i++) {
            if (dfs(i1, i2, i) && dfs(i1 + i, i2 + i, length - i)) {
                dp[i1][i2][length] = 1;
                return true;
            }


            if (dfs(i1, i2 - i + length, i) && dfs(i1 + i, i2, length - i)) {
                dp[i1][i2][length] = 1;
                return true;
            }
        }
        dp[i1][i2][length] = -1;
        return false;
    }

    public boolean simpleCheck(int index1, int index2, int length) {
        String s1 = this.s1.substring(index1, length);
        String s2 = this.s2.substring(index2, length);
        if (s1.length() != s2.length()) {
            return false;
        }

        Map<Character, Integer> map = new HashMap<>();
        for (char c : s1.toCharArray()) {
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        for (char c : s2.toCharArray()) {
            map.put(c, map.getOrDefault(c, 0) - 1);
        }
        for (Map.Entry<Character, Integer> entry : map.entrySet()) {
            if (entry.getValue() != 0) {
                return false;
            }
        }
        return true;
    }
}
